
/*
 * @(#)FormBuilderHelper.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.core;

import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.form.bean.FormData;
import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSection;
import com.dcivision.form.bean.FormSubmission;
import com.dcivision.form.dao.FormDataDAObject;
import com.dcivision.form.dao.FormDataElementDAObject;
import com.dcivision.form.dao.FormElementDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormSectionDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.dao.WorkflowStepDAObject;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PRAcroForm;
import com.lowagie.text.pdf.PRIndirectReference;
import com.lowagie.text.pdf.PdfArray;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfFormField;
import com.lowagie.text.pdf.PdfLister;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfNumber;
import com.lowagie.text.pdf.PdfObject;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfString;

/**
  FormBuilderHelper.java

  This class is responsible for workflow operation.

    @author          Tony Chen
    @company         DCIVision Limited
    @creation date   03/08/2003
    @version         $Revision: 1.30.2.2 $
*/

public class FormBuilderHelper {

  public static final String REVISION = "$Revision: 1.30.2.2 $";

  protected Log log = LogFactory.getLog(this.getClass().getName());
  private SessionContainer sessionCon = null;
  private Connection dbConn = null;

  /**
   * Constructor
   *
   * @param sessionContainer
   * @param conn
   */
  public FormBuilderHelper(SessionContainer sessionContainer, Connection conn) {
    this.sessionCon = sessionContainer;
    this.dbConn = conn;
  }

  public FormBuilderHelper() {
  }

  /**
   * Save as a file
   * @param oldUrl
   * @param newUrl
   */
  public void saveAsFile(String oldUrl,String newUrl) throws ApplicationException {
    try {
      FileInputStream fin = new FileInputStream(oldUrl);
      FileOutputStream fout = new FileOutputStream(newUrl);

      int line = 0;

      while( (line = fin.read()) != -1 ) {
        fout.write(line);
      }
      fin.close();
      fout.close();

    }catch (FileNotFoundException fnfex){
      throw new ApplicationException(fnfex);
    } catch (IOException ioex){
      throw new ApplicationException(ioex);
    }

  }

  /**
   * Generate form record data XML by the formRecordID ,formSubmissionID
   * @param request
   * @param response
   * @param formRecordID
   * @param formSubmissionID
   * @param navMode
   * @throws ApplicationException
   */
  public void generateXML(HttpServletRequest request,
      HttpServletResponse response,
      String formRecordID,
      String formSubmissionID,
      String navMode,
      String xmlPath,
      String isViewStep,
      String progressID,
      String userRecordID,
      Integer workflowStepID)throws ApplicationException {
    DocumentBuilder builder = null;
    try {
      DocumentBuilderFactory factory =
          DocumentBuilderFactory.newInstance();
      builder = factory.newDocumentBuilder();
    } catch (Exception ex) {
      log.error(ex, ex);
    }

    FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.sessionCon, this.dbConn);
    FormRecord formRecord =(FormRecord)formRecordDAO.getByFormRecordID(formRecordID);
    try {
      File file = new File(xmlPath);
      StringBuffer context = new StringBuffer();
      context.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
      context.append("<Form>\n");
      context.append("  <FormRecord ID = \"");
      context.append(formRecordID+"\"\n");
      context.append("              FormSubmissionID = \"");
      context.append(formSubmissionID + "\" \n");
      context.append("              navMode=\"");
      context.append(navMode+"\"\n");
      context.append("              isEdit=\"");
      context.append("true\"\n");
      context.append("              status=\"");
      context.append(formRecord.getStatus());
      context.append("\">");


      //String formPageID = null;
      //    get form page
      FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon, this.dbConn);
      FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.sessionCon, this.dbConn);
      FormElementDAObject formElementDAO = new FormElementDAObject(this.sessionCon, this.dbConn);
      FormDataElementDAObject formDataElementDAO = new FormDataElementDAObject(this.sessionCon, this.dbConn);
      FormDataDAObject formDataDAO = new FormDataDAObject(this.sessionCon, this.dbConn);

      List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(new Integer(formRecordID),workflowStepID);
      for (int i = 0; i < formPageList.size(); i++){
        FormPage formPage =(FormPage)formPageList.get(i);
        context.append( this.getPageInfo(formPage) );

         //get form section
        List formSectionList = formPage.getFormSectionList();
        for (int j=0; j<formSectionList.size(); j++){
          FormSection formSection = (FormSection)formSectionList.get(j);
          context.append(this.getSectinInfo(formSection));

          //get form element
          List formElementList = formSection.getFormElementList();
          for (int k = 0; k < formElementList.size(); k++) {
            FormElement formElement = (FormElement)formElementList.get(k);
            List formDataList = new ArrayList();
            if (!Utility.isEmpty(formSubmissionID)){
              if (!Utility.isEmpty(isViewStep) && !"null".equals(isViewStep)){
                Integer formDataSeqNo = new Integer(0);
                formDataSeqNo = formDataElementDAO.getFormDataSeqIDBySectionIDElementIDSubmissionIDWFProgressID(formSection.getID(), formElement.getID(), new Integer(formSubmissionID),new Integer(progressID),new Integer(userRecordID));
                if (!Utility.isEmpty(request.getParameter("isViewUserStep")) && "true".equals(request.getParameter("isViewUserStep")) && formDataSeqNo.intValue()>0){
                  //display submit for workflow list view step.
                  formDataList = formDataElementDAO.getElementValueByPageIDSectionIDSubmissionIDElementIDSeqNo(new Integer(formSubmissionID),formPage.getID(),formSection.getID(),formElement.getID(),formDataSeqNo,new Integer(userRecordID));
                }else{
                  formDataList = formDataElementDAO.getElementValueByPageIDSectionIDSubmissionIDElementID(
                      formPage.getID(),formSection.getID(),new Integer(formSubmissionID.trim()),formElement.getID());
                }
              }else{
                formDataList = formDataElementDAO.getElementValueByPageIDSectionIDSubmissionIDElementID(
                            formPage.getID(),formSection.getID(),new Integer(formSubmissionID.trim()),formElement.getID());
              }

            }
            context.append(this.getElementInfo(formElement,formDataList));
            context.append("\n        </Element>");
          }
          context.append("\n      </Section>");
        }
        context.append("\n    </Page>");
      }


      context.append("\n  </FormRecord>");
      context.append("\n</Form>");

      byte[] contextByte = context.toString().getBytes("UTF-8");
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(contextByte);

    } catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, e);
    } finally {}

  }

  /**
   * set page info into xml
   * @param formPage
   * @return
   */
  private StringBuffer getPageInfo(FormPage formPage){
    StringBuffer context = new StringBuffer();
    String formPageID = formPage.getID().toString();
    context.append("\n    <Page ID=\"");
    context.append(formPageID+"\"\n");
    context.append("               formRecordPermission=\"");
    context.append(formPage.getFormRecordPermission()+"\"\n");
    context.append("               pagePermission=\"");
    context.append(formPage.getPermission());
    context.append("\">");
    return context;
  }

  /**
   * set section info into xml
   * @param formSection
   * @return
   */
  private StringBuffer getSectinInfo(FormSection formSection){
    StringBuffer context = new StringBuffer();
    context.append("\n      <Section ID=\"");
    context.append(formSection.getID().toString()+"\"\n");
    context.append("               isSubSection=\"");
    context.append(formSection.getSubSection()+"\"\n");
    context.append("               sectionPermission=\"");
    context.append(formSection.getPermission());
    context.append("\">");
    return context;
  }

  /**
   * set element info into xml
   * @param formElement
   * @param formDataList
   * @return
   */
  private StringBuffer getElementInfo(FormElement formElement, List formDataList){
    StringBuffer context = new StringBuffer();
    String value = "";
    context.append("\n        <Element ID=\"");
    context.append(formElement.getID().toString());
    context.append("\"\n                 name=\"");
    context.append(formElement.getFieldName());
    context.append("\"\n                 isLabel=\"");
    context.append(formElement.getIsLabel().toString());
    context.append("\"\n                 elementPermission=\"");
    context.append(formElement.getPermission().toString());
    context.append("\"\n                 value=\"");
    if(!Utility.isEmpty(formDataList)){
      for(int i=0; i<formDataList.size(); i++){
        FormData formData = (FormData)formDataList.get(i);
        if (!Utility.isEmpty(formData.getDataString())){
          value += TextUtility.htmlEncode(formData.getDataString());// +"|";
        }else{
          value += " ";// +"|";
        }
      }
      context.append(value);
    }
    context.append("\">");
    return context;
  }

  /**
   * Returns the AcroForm fields with fieldName and bounding box coordinates as attributes
   * @param PdfReader reader
   * @return org.w3c.dom.Document
   */
  public org.w3c.dom.Document getFields(PdfReader reader) {
    try {
      String[] sRect = new String[] { "x1", "y1", "x2", "y2" };

      PRAcroForm form = reader.getAcroForm();
      if (form == null) {
        log.info("This document has no fields.");
        return null;
      }
      // Create an empty DOM document
      org.w3c.dom.Document fieldDoc = createDomDocument();
      org.w3c.dom.Element xmlSections = fieldDoc.createElement("Page");
      fieldDoc.appendChild(xmlSections);
      PdfLister list = new PdfLister(System.out);
      HashMap refToField = new HashMap();
      ArrayList fields = form.getFields();
      ArrayList tmpElementArr = new ArrayList();
      for (int k = 0; k < fields.size(); ++k) {
        PRAcroForm.FieldInformation field = (PRAcroForm.FieldInformation)fields.get(k);
        refToField.put(new Integer(field.getRef().getNumber()), field);
      }
      for (int page = 1; page <= reader.getNumberOfPages(); ++page) {
        PdfDictionary dPage = reader.getPageN(page);
        PdfArray annots = (PdfArray)reader.getPdfObject(dPage.get(PdfName.ANNOTS));
        if (annots == null) {
          continue;
        }
        ArrayList ali = annots.getArrayList();
        String[] tmpElementStr = new String[ali.size()];
        for (int annot = 0; annot < ali.size(); ++annot) {
          PdfObject refObj = (PdfObject)ali.get(annot);
          PRIndirectReference ref = null;
          PdfDictionary an = (PdfDictionary)reader.getPdfObject(refObj);
          PdfName name = (PdfName)an.get(PdfName.SUBTYPE);
          if (name == null || !name.equals(PdfName.WIDGET)){
            continue;
          }
          PdfArray rect = (PdfArray)reader.getPdfObject(an.get(PdfName.RECT));
          String fName = "";
          PRAcroForm.FieldInformation field = null;
          String sType = "";
          while (an != null) {
            PdfString tName = (PdfString)an.get(PdfName.T);
            PdfName type = (PdfName)an.get(PdfName.FT);
            if (PdfName.SIG.equals(type)){
              sType = "SECTION";
            }else if (PdfName.TX.equals(type)){
              sType = "T";
            }else if (PdfName.BTN.equals(type)) {
              PdfNumber ff =  (PdfNumber)an.get(PdfName.FF);
              int flags = 0;
              if (ff != null){
                flags = ff.intValue();
                if (flags == PdfFormField.FF_COMBO){
                  sType = "S";
                }else if (flags == PdfFormField.FF_PUSHBUTTON){
                  sType = "B";
                }else {
                  sType = "R";
                }
              }else{
                sType = "C";
              }

            }else if(PdfName.CH.equals(type)){
              sType = "S";
            }
            if (tName != null)
              fName = tName.toString() + "." + fName;
            if (refObj.type() == PdfObject.INDIRECT && field == null) {
              ref = (PRIndirectReference)refObj;
              field = (PRAcroForm.FieldInformation)refToField.get(new Integer(ref.getNumber()));
            }
            refObj = an.get(PdfName.PARENT);
            an = (PdfDictionary)reader.getPdfObject(refObj);
          }
          if (fName.endsWith(".")) {
            fName = fName.substring(0, fName.length() - 1);
          }
          ArrayList arr = rect.getArrayList();
          for (int r = 0; r < 4; ++r) {
            PdfNumber num = (PdfNumber)reader.getPdfObject((PdfObject)arr.get(r));
            //Add the "field" to String[] for sort by position.
            if (r==1){
              String sTmpNum = "";
              String sTmpPreNum = num.toString().substring(0,num.toString().indexOf("."));
              if (sTmpPreNum.length()<4){
                for (int n=0; n<4-sTmpPreNum.length(); n++){
                  sTmpNum += "0";
                }
              }
              tmpElementStr[annot]= sTmpNum+num.toString()+","+fName+","+sType;
            }
          }
        }

        //sort by position
        Arrays.sort(tmpElementStr);
        int sectionSeqNO = 1;
        org.w3c.dom.Element xmlSection = null;
        for (int ii=tmpElementStr.length-1; ii>=0; ii--){
          String[] tmpStr = TextUtility.splitString(tmpElementStr[ii],",");
          if (tmpStr[2].toString().equals("SECTION")){
            if (sectionSeqNO > 1){
              xmlSections.appendChild(xmlSection);
            }
            xmlSection = fieldDoc.createElement("Section");
            tmpElementStr[ii] = tmpStr[0]+","+"Section"+sectionSeqNO;
            // Add section
            xmlSection.setAttribute("Page", String.valueOf(page));
            xmlSection.setAttribute("SectionName", "Section"+sectionSeqNO);
            sectionSeqNO ++;
          }else{
            // Add the "field" element
            org.w3c.dom.Element xmlField = fieldDoc.createElement("Field");
            xmlField.setAttribute("FieldName", tmpStr[1]);
            xmlField.setAttribute("FieldType", tmpStr[2]);
            //Append the field element to fields element
            xmlSection.appendChild(xmlField);
          }
        }
        xmlSections.appendChild(xmlSection);
      }
      return fieldDoc;
      } catch(Exception e) {
        log.debug(e);
      }
      return null;
  }

  /**
   * Create an empty dom Document
   * @return org.w3c.dom.Document
   */
  public org.w3c.dom.Document createDomDocument() {
      try {
          DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
          org.w3c.dom.Document doc = builder.newDocument();
          return doc;
      } catch (ParserConfigurationException e) {
      }
      return null;
  }

  public void loadURL(String pdfFile,String loadButtonPdfFile,String xmlPath,
                      String formRecordID,String url,String navMode,Integer workflowStepID,
                      String isViewTask,String progressID,String workflowRecordID, String appendUrl) throws ApplicationException {
    //this.saveAsFile(pdfFile,loadButtonPdfFile);
    try{
      SessionContainer sessionContainer = this.sessionCon;
      PdfReader pdfReader;
      String saveStatus = FormSubmission.FORM_SUBMISSION_STATU_SAVED;
      String submitStatus = FormSubmission.FORM_SUBMISSION_STATU_COMPLETED;

      pdfReader = new PdfReader(pdfFile);
      PdfStamper stamper = new PdfStamper(pdfReader, new FileOutputStream(loadButtonPdfFile));
      AcroFields af = stamper.getAcroFields();
      AcroFields.Item itemSave = af.getFieldItem("Save"); //your save field name
      AcroFields.Item item = af.getFieldItem("Submit"); //your submit field name
      PdfDictionary wSave = (PdfDictionary)itemSave.widgets.get(0); //repeat from 0-size()
      PdfDictionary w = (PdfDictionary)item.widgets.get(0); //repeat from 0-size()
      PdfDictionary aSave = (PdfDictionary)PdfReader.getPdfObject(wSave.get(PdfName.A));
      PdfDictionary a = (PdfDictionary)PdfReader.getPdfObject(w.get(PdfName.A));
      PdfDictionary fSave = new PdfDictionary();
      PdfDictionary f = new PdfDictionary();
      fSave.put(PdfName.FS, PdfName.URL);

      String allUrl=url+"/form/GenerateXML.do?formRecordID="+formRecordID+"&xmlPath="+xmlPath+"&status=R&navMode="+navMode+"&isViewTask="+isViewTask+"&progressID="+progressID+"&workflowRecordID="+workflowRecordID;
      if (!Utility.isEmpty(appendUrl)){
        allUrl=allUrl+appendUrl;
      }
      fSave.put(PdfName.F, new PdfString(allUrl+"&submitStatus="+saveStatus));
      aSave.put(PdfName.F, fSave);
      f.put(PdfName.FS, PdfName.URL);
      f.put(PdfName.F, new PdfString(allUrl+"&submitStatus="+submitStatus));
      a.put(PdfName.F, f);

      stamper.close();
      //delete disableEle file.
      //File delFile = new File(pdfFile);
      //delFile.delete();

    } catch (Exception ioex){
      log.info(ioex);
      throw new ApplicationException(ioex);
    }
  }

  /**
   *
   * @param pdfPath
   * @param viewPdfPath
   * @param formRecordID
   * @param workflowStepID
   * @param isViewTask
   * @throws ApplicationException
   */
  public void setFormFieldsReadOnly(String pdfPath,String viewPdfPath,String formRecordID,Integer workflowStepID,String isViewTask,String navMode,String function)throws ApplicationException{
    try{
      //this.saveAsFile(pdfPath,viewPdfPath);
      PdfReader reader = new PdfReader(pdfPath);
      FileOutputStream fo = new FileOutputStream(viewPdfPath);
      PdfStamper stamp = new PdfStamper(reader, fo);
      AcroFields form = stamp.getAcroFields();

      FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon, this.dbConn);
      FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.sessionCon, this.dbConn);
      FormElementDAObject formElementDAO = new FormElementDAObject(this.sessionCon, this.dbConn);
      FormDataElementDAObject formDataElementDAO = new FormDataElementDAObject(this.sessionCon, this.dbConn);
      FormDataDAObject formDataDAO = new FormDataDAObject(this.sessionCon, this.dbConn);
      WorkflowStepDAObject workflowStepDAObj =  new  WorkflowStepDAObject(this.sessionCon, this.dbConn);

      List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(new Integer(formRecordID),workflowStepID);
      Integer pageID = null,sectionID= null;

      //boolean isWorkflowProcess = false;
      boolean hasCheckPermission = false;
      String pagePermission="",sectionPermission="",elementPermission="";
      String isElementChange="false",isElementRead="false",isElementDisabled="true";
      if (!Utility.isEmpty(workflowStepID) && workflowStepID.intValue()>0){
        hasCheckPermission = true;
      }
//      if (!Utility.isEmpty(isViewTask) && "N".equals(isViewTask)){
//        isWorkflowProcess = true;
//      }
      for (int i = 0; i < formPageList.size(); i++){
        FormPage formPage =(FormPage)formPageList.get(i);
        pageID = formPage.getID();
        String formRecordPermission = formPage.getFormRecordPermission();
        pagePermission =  formPage.getFormRecordPermission();
        pagePermission = this.getPagePermission(formRecordPermission,pagePermission,hasCheckPermission);
        //get form section
        List formSectionList = formPage.getFormSectionList();
        for (int j=0; j<formSectionList.size(); j++){
          FormSection formSection = (FormSection)formSectionList.get(j);
          sectionID = formSection.getID();
          sectionPermission = formSection.getPermission();
          sectionPermission = this.getSectionPermission(pagePermission,sectionPermission,hasCheckPermission);
          //if ((!Utility.isEmpty(isViewTask) && !"null".equals(isViewTask) && !isStepEdit) ){//if the section is not able to edit and view , don't disp this section
            //get form element
          List formElementList = formSection.getFormElementList();
          for (int k = 0; k < formElementList.size(); k++) {
            FormElement formElement = (FormElement)formElementList.get(k);
            elementPermission = formElement.getPermission();
            elementPermission = this.getElementPermission(sectionPermission,elementPermission,hasCheckPermission);
            String[] permissionArr = TextUtility.splitString(elementPermission,"|");
            isElementChange = permissionArr[0].toString();
            isElementRead = permissionArr[1].toString();
            isElementDisabled = permissionArr[2].toString();
            if ((GlobalConstant.NAV_MODE_VIEW.equals(navMode)&& !"FORMSETUP".equals(function)) || isViewTask.equals("Y") ){  //view
              if ("true".equals(isElementChange)){
                isElementChange = "false";
                isElementRead = "true";
              }
            }
            if (!"true".equals(isElementChange)){
              if ("N".equals(formElement.getIsLabel()) && !formElement.getElementType().equals(FormElementType.ELEMENT_RADIO_BUTTON)){
                form.setFieldProperty(formElement.getFieldName(),"bgcolor",new Color(232,232,232),null);
                form.setField(formElement.getFieldName(),"");
              }
              AcroFields.Item item = form.getFieldItem(formElement.getFieldName());
              PdfDictionary dic = (PdfDictionary)item.widgets.get(0);
              PdfObject pdfobj = dic.get(PdfName.FF);
              dic.put(PdfName.FF,new PdfNumber(PdfFormField.FF_READ_ONLY));
            }
          }
           //Handel is Label Element
           List isLabelElementList = formElementDAO.getIsLabelElementListByFormSectionID(sectionID);
           for (int nn=0; nn<isLabelElementList.size(); nn++){
              FormElement formElement = (FormElement)isLabelElementList.get(nn);
             AcroFields.Item item = form.getFieldItem(formElement.getFieldName()); //your save field name
            PdfDictionary dic = (PdfDictionary)item.widgets.get(0);
            PdfObject pdfobj = dic.get(PdfName.FF);
            dic.put(PdfName.FF,new PdfNumber(PdfFormField.FF_READ_ONLY));
           }
          //}
        }
      }
      if(GlobalConstant.NAV_MODE_VIEW.equals(navMode)){
        AcroFields.Item itemSave = form.getFieldItem("Save"); //your save field name
        AcroFields.Item itemSubmit = form.getFieldItem("Submit"); //your submit field name
        PdfDictionary dicSave = (PdfDictionary)itemSave.widgets.get(0);
        PdfObject pdfobjSave = dicSave.get(PdfName.FF);
        dicSave.put(PdfName.FF,new PdfNumber(PdfFormField.FLAGS_INVISIBLE));
        PdfDictionary dicSubmit = (PdfDictionary)itemSubmit.widgets.get(0);
        PdfObject pdfobjSubmit = dicSubmit.get(PdfName.FF);
        dicSubmit.put(PdfName.FF,new PdfNumber(PdfFormField.FLAGS_INVISIBLE));
      }
      stamp.close();
    } catch (Exception ioex){
      log.info(ioex);
      throw new ApplicationException(ioex);
    }
  }

  public String getPagePermission(String formRecordPermission,String pagePermission,boolean hasCheckPermission){
    if (hasCheckPermission){
      if (Utility.isEmpty(pagePermission) || "null".equals(pagePermission)){
         pagePermission = formRecordPermission;
       }
       if (WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(pagePermission)){
         pagePermission = WorkflowStep.FORM_PROCESS_PERMISSION_CHANGE;
       }
    }
    return pagePermission;
  }

  public String getSectionPermission(String pagePermission,String sectionPermission,boolean hasCheckPermission){
    if (hasCheckPermission){
      if (Utility.isEmpty(sectionPermission) || "null".equals(sectionPermission)){
        sectionPermission = pagePermission;
      }
      if (WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(sectionPermission)){
         sectionPermission = WorkflowStep.FORM_PROCESS_PERMISSION_CHANGE;
      }
    }
    return sectionPermission;
  }

  public String getElementPermission(String sectionPermission,String elementPermission,boolean hasCheckPermission){
    boolean isStepElementChange = false,isStepElementRead = false,isStepElementDisabled = false;
    if (hasCheckPermission){
      if (Utility.isEmpty(elementPermission) || "null".equals(elementPermission)){
        elementPermission = sectionPermission;
      }
      if (WorkflowStep.FORM_PROCESS_PERMISSION_READ.equals(elementPermission)){
        isStepElementChange = false;
        isStepElementRead = true;
        isStepElementDisabled = false;
      } else if (WorkflowStep.FORM_PROCESS_PERMISSION_CHANGE.equals(elementPermission)){
        isStepElementChange = true;
        isStepElementRead = false;
        isStepElementDisabled = false;
      } else {
        isStepElementDisabled = true;
      }
    }else{
      isStepElementDisabled = false;
      isStepElementChange = true;
      isStepElementRead = false;
    }

    return (isStepElementChange+"|"+isStepElementRead+"|"+isStepElementDisabled);
  }
}